import { RouteRecordRaw } from 'vue-router'
import { IBreadcrumb } from '@/base-ui/breadcrumb'
let firstMenu: any = null
export function mapMenusToRoutes(userMenus: any[]): RouteRecordRaw[] {
  //初始化一个route对象 userMenus为全部的路径
  const routes: RouteRecordRaw[] = []

  // 1.先去加载默认所有的routes 在本地已经创建过的
  const allRoutes: RouteRecordRaw[] = []
  //在router/main文件夹下面所有的以ts结尾的文件 切开启递归扫瞄
  const routeFiles = require.context('../router/main', true, /\.ts/)
  //对拿到的文件进行循环 拿到正确的映射地址 和映射配置 如system文件中user里面的配置
  routeFiles.keys().forEach((key) => {
    //因为key还不是一网站的地址 我们要进行完整地址的拼接 因为key前面是 ./user 这样的形式所以要进行切割 删除.
    const route = require('../router/main' + key.split('.')[1])
    allRoutes.push(route.default)
  })

  /*查看本地所有已经建立好的路由 后面根据后端传入的路由来动态选择要哪些
console.log(allRoutes)
  */
  // 2.根据菜单获取需要添加的routes
  //对后端传入的menus进行递归拿到里面的路径
  // userMenus:分两种情况
  //修改东西主要看这个递归的函数
  // type === 1 -> children -> type === 1
  // type === 2 -> url -> route
  const _recurseGetRoute = (menus: any[]) => {
    for (const menu of menus) {
      if (menu.type === 2) {
        //从allRoutes数组中寻找对象 拿传入的url去route映射中找有就返回
        const route = allRoutes.find((route) => route.path === menu.url)

        //如果找到了则写进routes对像
        if (route) routes.push(route)

        if (!firstMenu) {
          firstMenu = menu
        }
      } else {
        //在type不等2是进行递归传入子元素
        _recurseGetRoute(menu.children)
      }
    }
  }

  _recurseGetRoute(userMenus)

  return routes
}
//面包屑
export function pathMapBreadcrumbs(userMenus: any[], currentPath: string) {
  const breadcrumbs: IBreadcrumb[] = []
  pathMapToMenu(userMenus, currentPath, breadcrumbs)
  return breadcrumbs
}

// /main/system/role  -> type === 2 对应menu
export function pathMapToMenu(
  userMenus: any[],
  currentPath: string,
  breadcrumbs?: IBreadcrumb[]
): any {
  for (const menu of userMenus) {
    if (menu.type === 1) {
      const findMenu = pathMapToMenu(menu.children ?? [], currentPath)
      if (findMenu) {
        breadcrumbs?.push({ name: menu.name })
        breadcrumbs?.push({ name: findMenu.name })
        return findMenu
      }
    } else if (menu.type === 2 && menu.url === currentPath) {
      return menu
    }
  }
}

export function menuMapLeafKeys(menuList: any[]) {
  const leftKeys: number[] = []

  const _recurseGetLeaf = (menuList: any[]) => {
    for (const menu of menuList) {
      if (menu.children) {
        _recurseGetLeaf(menu.children)
      } else {
        leftKeys.push(menu.id)
      }
    }
  }
  _recurseGetLeaf(menuList)

  return leftKeys
}
export { firstMenu }
